#include "Player.hh"
#include <iostream>

using namespace std;

// 玩家类构造函数,初始化基本属性
Player::Player(int id, const std::string& name, int hp, int maxhp, int atk, int def, int speed)
    : id_(id), name_(name), hp_(hp), maxhp_(maxhp), atk_(atk), def_(def), speed_(speed) {}

// 速度属性
int speed_;

// 判断玩家是否存活
bool Player::isAlive() const {
    return hp_ > 0;
}

// 处理玩家受到的伤害
bool Player::takeDamage(unsigned damage) {
    if (damage >= hp_) hp_ = 0;
    else hp_ -= damage;
    return isAlive();
}

// 玩家攻击目标
bool Player::attack(ICharacter& target) {
    unsigned damage = atk_ > target.getDefense() ? atk_ - target.getDefense() : 0;
    cout << name_ << " attacked " << target.getName() << " dealing " << damage << " damage." << endl;
    return target.takeDamage(damage);
}

// 获取玩家基本属性
std::string Player::getName() const { return name_; }
std::string Player::getDescription() const { return "This is a brave player"; }
unsigned Player::getHealth() const { return hp_; }
unsigned Player::getAttack() const { return atk_; }
unsigned Player::getDefense() const { return def_; }
unsigned Player::getmaxHealth() const { return maxhp_; }
int Player::getSpeed() const { return speed_; }

// 设置玩家速度,限制在0-100之间
void Player::setSpeed(int speed) {
    if (speed < 0) speed_ = 0;
    else if (speed > 100) speed_ = 100;
    else speed_ = speed;
}

// 生成玩家状态描述字符串
std::string Player::toString() const {
    return "Player: " + name_ +
           " HP: " + to_string(hp_) + "/" + to_string(maxhp_) +
           " ATK: " + to_string(atk_) +
           " DEF: " + to_string(def_) +
           " SPD: " + to_string(speed_);
}

// 向玩家背包添加物品
void Player::addToInventory(Item* item) {
    if (item) {
        bag_.addItem(*item);
        cout << "Acquired item:" << item->getName() << endl;
    }
}

// 显示背包内容
void Player::displayInventory() const {
    bag_.showItems();
}

// 显示玩家状态
void Player::display() const {
    cout << toString() << endl;
}

// 获取背包引用
Inventory& Player::getInventory() {
    return bag_;
}

// 回复玩家生命值
void Player::heal(int amount) {
    hp_ += amount;
    if (hp_ > maxhp_) hp_ = maxhp_;
    cout << name_ << " healed " << amount << " HP, current HP:" << hp_ << "/" << maxhp_ << endl;
}

// 从JSON读取玩家数据
void from_json(const json& j, Player& p) {
    j.at("id").get_to(p.id_);
    j.at("name").get_to(p.name_);
    j.at("hp").get_to(p.hp_);
    j.at("maxhp").get_to(p.maxhp_);
    j.at("atk").get_to(p.atk_);
    j.at("def").get_to(p.def_);
    j.at("speed").get_to(p.speed_);
}

// 将玩家数据转换为JSON
void to_json(json& j, const Player& p) {
    j = json{
        {"id", p.id_},
        {"name", p.name_},
        {"hp", p.hp_},
        {"maxhp", p.maxhp_},
        {"atk", p.atk_},
        {"def", p.def_},
        {"speed", p.speed_}
    };
}

// 设置玩家属性的方法
void Player::setAttack(unsigned atk) { atk_ = atk; }
void Player::setDefense(unsigned def) { def_ = def; }
void Player::setHpMax(unsigned maxhp) {
    maxhp_ = maxhp;
    if (hp_ > maxhp_) hp_ = maxhp_;
}